package com.zzj.portalwebsite.Dao.Impl;

import com.zzj.portalwebsite.Dao.FeedBackDao;
import com.zzj.portalwebsite.entity.FeedBack;
import com.zzj.portalwebsite.utlis.ConnectionDatabaseForMySQLUseJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FeedBackDaoImpl implements FeedBackDao {


    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet resultSet = null;

    public FeedBackDaoImpl(){
        connection = ConnectionDatabaseForMySQLUseJdbc.getConnection();

        System.out.println(connection);

    }
    @Override
    public boolean subInfo(FeedBack feedback) throws Exception {

        if (null == connection){
            return false;
        }

        pstmt = connection.prepareStatement("insert into p_feedback(u_name,u_email,u_phone,message,create_time,backimg) values (?,?,?,?,?,?)");
        pstmt.setString(1,feedback.getU_name());
        pstmt.setString(2,feedback.getU_email());
        pstmt.setString(3,feedback.getU_phone());
        pstmt.setString(4,feedback.getMessage());
        pstmt.setTimestamp(5,new java.sql.Timestamp(System.currentTimeMillis()));
        pstmt.setString(6,feedback.getBackimg());
        int i = pstmt.executeUpdate();

        return i==1?true:false;

    }

    @Override
    public List<FeedBack> getFeedBack(int pageNum, int pageSize) throws SQLException {
        List<FeedBack> list = new ArrayList<>();
        if (null == connection) {
            return null;
        }
        int offset = (pageNum - 1) * pageSize;
        pstmt = connection.prepareStatement("select id,u_name,u_email,u_phone,message,create_time,backimg from p_feedback limit ? offset ?");
        pstmt.setInt(1, pageSize + 1); // 多查询一条记录，用于判断是否有下一页
        pstmt.setInt(2, offset);
        resultSet = pstmt.executeQuery();

        while (resultSet.next()) {
            list.add(new FeedBack(
                    resultSet.getInt("id"),
                    resultSet.getString("u_name"),
                    resultSet.getString("u_email"),
                    resultSet.getString("u_phone"),
                    resultSet.getString("message"),
                    resultSet.getTimestamp("create_time"),
                    resultSet.getString("backimg")
            ));
        }
        return list;
    }

    @Override
    public boolean deleteFeedBack(int id) throws SQLException {
        if (null == connection) {
            return false;
        }
        PreparedStatement pstmt = connection.prepareStatement("delete from p_feedback where id = ?");
        pstmt.setInt(1, id);
        int i = pstmt.executeUpdate();
        return i == 1;
    }
}
